package com.stefan.array;


public class StefanList<E> {
    private Object[] data;
    private int size; //数组实际存储的元素个数
    private int capacity; // current used index

    public StefanList(int capacity) {
        this.capacity = capacity;
        this.data = new Object[capacity];
        this.size = 0;
    }

    public void add(E value) {
        add(size,value);
//        if (size < capacity) {
//            data[size++] = value; //size++是先使用size然后在+1
//        } else {
//            //resize
//            resize();
//            data[size++] = value;
//        }
    }
    public void add(int index,E value) {
        //判断插入的index是不是大于数组size
        if (index > size) {
            throw new IndexOutOfBoundsException();
        }
        // 当插入该元素的时候数组的size大于数组容量时
        if (++size > capacity) {
            //扩容 resize
            resize();
        }
        //移动元素
        for (int i = size-1; i>index; i--) {
            data[i] = data[i-1] ;
        }
        //插入元素
        data[index] = value;
    }
    public E get(int index) {
        return (E)data[index];
    }
    public E remove(int index) {
        //判断插入的index是不是大于数组size
        if (index > size - 1) {
            throw new IndexOutOfBoundsException();
        }
        E result = (E) data[index];
        for (int i = index; i < size; i++) {
            if (i != size-1) {
                data[i] = data[i+1];
            } else {
                data[i] = null;
            }
        }
        size--;
        return result;
    }
    private void resize() {
        System.out.println("扩容千 capacity: "+capacity);
        this.capacity = this.capacity<<1;
        System.out.println("扩容后 capacity: "+capacity);
        Object[] copy = new Object[capacity];
        for (int i = 0; i < data.length; i++) {
            copy[i] = data[i];
        }
        this.data = copy;
    }


    public static void main(String[] args) {
        StefanList<String> s = new StefanList(3);
        s.add("1");
        s.add("2");
        s.add("3");
        s.add("4");
        s.add("5");
        s.add("6");


        s.add(6,"9");

        String remove = s.remove(2);
        String get = s.get(2);
        System.out.println("===");

    }

}
